#include "device.h"
#include <QNetworkInterface>

Device::Device(QObject *parent) : QObject(parent)
{
    m_udpSocket = new QUdpSocket(this);
    m_discoveryTimer = new QTimer(this);
    connect(m_udpSocket, &QUdpSocket::readyRead, this, &Device::readPendingDatagrams);
}

void Device::startDiscovery()
{
    m_udpSocket->bind(45454, QUdpSocket::ShareAddress);
    //每5s发送一次发现广播
    connect(m_discoveryTimer, &QTimer::timeout, [this]()
    {
        QByteArray datagram = "EDGE_GAYEWAY_DISCOVERY";
        foreach (const QNetworkInterface &interface, QNetworkInterface::allInterfaces()) {
            foreach (const QNetworkAddressEntry &entry, interface.addressEntries()) {
                if(entry.broadcast().toString().isEmpty()) continue;
                m_udpSocket->writeDatagram(datagram,entry.broadcast(),45455);
            }

        }
    });
    m_discoveryTimer->start(5000);
}

void Device::readPendingDatagrams()
{
    while(m_udpSocket->hasPendingDatagrams())
    {
        QByteArray dataram;
        dataram.resize(m_udpSocket->pendingDatagramSize());
        QHostAddress sender;

        m_udpSocket->readDatagram(dataram.data(), dataram.size(), &sender);

        if(dataram.startsWith("EDGE_DEVICE_RESPONSE"))
        {
            emit deviceFound(sender.toString(), QString(dataram.mid(21)));
        }
    }
}
